package com.eagle.web.http.converter.properties;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Properties;

public class MappingProperties2HttpMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {
	public MappingProperties2HttpMessageConverter() {
		super(new MediaType("text","properties"));
	}

	@Override
	protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		OutputStream body = outputMessage.getBody();
		HttpHeaders headers = outputMessage.getHeaders();
		MediaType contentType = headers.getContentType();
		Charset charset = contentType.getCharset();
		charset = charset != null ? charset : Charset.forName("UTF-8");
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body,charset);

		properties.store(outputStreamWriter,"From MappingProperties2HttpMessageConverter");
	}

	@Override
	protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		HttpHeaders headers = inputMessage.getHeaders();
		MediaType contentType = headers.getContentType();
		Charset charset = contentType.getCharset();
		charset = charset != null ? charset : Charset.forName("UTF-8");

		InputStream body = inputMessage.getBody();
		InputStreamReader inputStreamReader = new InputStreamReader(body, charset);
		Properties properties = new Properties();

		properties.load(inputStreamReader);
		return properties;
	}

	@Override
	public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		return readInternal(null, inputMessage);
	}
}
